package com.shijf.ds;

/**
 * @Author shijf
 * @Description //基于数组实现的栈
 * 栈是先入后出原则
 * @Date 14:55 2023/10/26
 **/
public class ArrayStack {
    private int[] arr;
    private int top;

    public ArrayStack(int capacity) {
        arr = new int[capacity];
        top = -1;
    }

    //入栈
    public void push(int value) {
        if (top == arr.length - 1) {
            throw new RuntimeException("栈已满，无法入栈");
        }
        //arr中的++top 先执行。++top 是top先+1 然后再使用top
        arr[++top] = value;
    }

    //出栈
    public int pop() {
        if (top == -1) {
            throw new RuntimeException("栈为空，无法出栈");
        }
        //top-- 是top先使用后，再减1
        return arr[top--];
    }

    //查询栈顶元素
    public int peek(){
        if(top == -1){
            throw new RuntimeException("栈为空，无法查看栈顶元素");
        }

        return arr[top];
    }


    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(5);
        //arrayStack.peek();
        arrayStack.push(100);
        arrayStack.push(82);
        arrayStack.push(10);
        arrayStack.push(15);
        arrayStack.push(60);

        for(int i=0 ;i<5 ;i++){
            System.out.println(arrayStack.peek());
            arrayStack.pop();
        }
    }
}
